package com.xj.zhihudemo.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.xj.zhihudemo.R;
import com.xj.zhihudemo.mode.LastNewsInfo;
import com.xj.zhihudemo.retrofit.ApiClient;
import com.xj.zhihudemo.retrofit.ApiStore;
import com.xj.zhihudemo.ui.adapter.TestMainAdapter;
import com.xj.zhihudemo.ui.listener.RecyclerViewLoadMoreListener;
import com.xj.zhihudemo.utils.ToastUtils;
import com.xj.zhihudemo.widget.ScrollBanner;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.OVER_SCROLL_NEVER;

/**
 * Created by Xujing on 16/9/1.
 */
public class MainFragment extends Fragment
        implements RecyclerViewLoadMoreListener.OnLoadMoreListener,
        SwipeRefreshLayout.OnRefreshListener {
    private final static String TAG = MainFragment.class.getSimpleName();
    private static MainFragment instance;
    @BindView(R.id.rv_main)
    RecyclerView mHomeRecyclerView;
    @BindView(R.id.srl_main)
    SwipeRefreshLayout mHomeSwipeRefreshLayout;
    private ArrayList<Integer> idList;

    //    @BindView(R.id.asb_topBanner)
//    ScrollBanner mAsbTopBanner;
    private ScrollBanner mAsbTopBanner;

    private TestMainAdapter mMainNewsAdapter;
    //    private MainNewsAdapter mMainNewsAdapter;
    private LinearLayoutManager mLayoutManager;
    private List<String> mAutoBanner = new ArrayList<String>();
    private Context mContext;

    private View mHeaderView;

    public static MainFragment getInstance() {
        if (instance == null) {
            instance = new MainFragment();
        }
        return instance;
    }


    @Override
    public void onAttach(Context context) {
        Log.d(TAG, "onAttach");
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        idList = new ArrayList<>();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
            container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View layout = inflater.inflate(R.layout.fragment_home, container,
                false);
        ButterKnife.bind(this, layout);
        return layout;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onViewCreated");
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
        initView();
    }


    /**
     * 初始化Themes数据
     */
    private void initData() {
        Log.d(TAG, "initThemesData()");
        ApiStore apiStore = ApiClient.retrofit().create(ApiStore.class);
        Call<LastNewsInfo> lastNewsInfoCall = apiStore.getLastNews("latest");
        lastNewsInfoCall.enqueue(new Callback<LastNewsInfo>() {
            @Override
            public void onResponse(Call<LastNewsInfo> call,
                                   Response<LastNewsInfo> response) {
                Log.d(TAG, "success");
                LastNewsInfo lastNewsInfo = response.body();
                List<LastNewsInfo.TopStoriesEntity> mBannerList = new ArrayList<LastNewsInfo.TopStoriesEntity>();
                if (lastNewsInfo != null) {
                    String date = lastNewsInfo.getDate();
                    Log.d(TAG, date);

                    mBannerList.addAll(lastNewsInfo.getTop_stories());
                    mAutoBanner.clear();
                    for (int i = 0; i < mBannerList.size(); i++) {

                        mAutoBanner.add(mBannerList.get(i).getImage());

                    }
                    Log.d(TAG, "list数目" + mBannerList.size() + "");
                    Log.d(TAG, "自定义控件数量" + mAutoBanner.size() + "");
                    mMainNewsAdapter.addData(lastNewsInfo);

                    mAsbTopBanner.setImagesUrl(mAutoBanner);
                    mAsbTopBanner.setDelayTime(4000);
                    mAsbTopBanner.setAutoPlaying(true);
//                    mAsbTopBanner.setOnItemClickListener(new ScrollBanner.OnItemClickListener() {
//                        @Override
//                        public void onItemClick(int position) {
//                            ToastUtils.with(mContext).show("点击了第" + position + "张图片");
//
//                        }
//                    });
//                    mAsbTopBanner.setImagesUrl();
//                    mAsbTopBanner.setImagesUrl(mBannerList.get());
                }
            }

            @Override
            public void onFailure(Call<LastNewsInfo> call, Throwable t) {

            }
        });


    }

    private void initView() {


        mHomeSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mHomeSwipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light
        );
        mHomeSwipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));


        mLayoutManager = new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false);
        mHomeSwipeRefreshLayout.setOnRefreshListener(this);
        mHomeRecyclerView.setOnScrollListener(new RecyclerViewLoadMoreListener(mLayoutManager, this, 10));

        mMainNewsAdapter = new TestMainAdapter(mContext);
//        mMainNewsAdapter = new MainNewsAdapter(mContext);
        idList.addAll(mMainNewsAdapter.getIdList());
        Log.e("length", idList.size() + "");
        mHomeRecyclerView.setHasFixedSize(true);
        mHomeRecyclerView.setOverScrollMode(OVER_SCROLL_NEVER);
        mHomeRecyclerView.setLayoutManager(mLayoutManager);
        mHomeRecyclerView.setAdapter(mMainNewsAdapter);
        initHeader(mHomeRecyclerView);
        mMainNewsAdapter.addHeader(mAsbTopBanner);
//        mMainNewsAdapter.setOnItemClick(new MainNewsAdapter.OnItemClickHelper
//                () {
//
//            @Override
//            public void onItemClick(View view, int position, LastNewsInfo.StoriesEntity data, ArrayList<Integer> idList) {
////                ToastUtils.with(mContext).show("click" + position);
//                Log.d(TAG, "click" + position);
//                Intent intent = new Intent();
//                intent.setClass(mContext, WebActivity.class);
//                intent.putExtra("index", idList.indexOf(data.getId()));
//                intent.putExtra("ids", idList);
//                Log.e("length", idList.size() + "");
//                Log.e("index", idList.indexOf(data.getId()) + "");
//                startActivity(intent);
//            }
//
//            @Override
//            public void onItemLongClick(View view, int position, LastNewsInfo
//                    .StoriesEntity data) {
//
//            }
//        });


    }

    private void initHeader(RecyclerView homeRecyclerView) {
        mHeaderView = LayoutInflater.from(mContext).inflate(R.layout.layout_mainfragment_header, homeRecyclerView, false);

        mAsbTopBanner = (ScrollBanner) mHeaderView.findViewById(R.id.asb_topBanner);
    }


    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    /**
     * 初始化顶部Banner数据
     */
    private void initBannerData() {
    }


    //下拉刷新
    @Override
    public void onRefresh() {

        Log.d(TAG, "下拉刷新");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                mHomeSwipeRefreshLayout.setRefreshing(false);
                ToastUtils.with(mContext).show("刷新完毕");
            }
        }, 3000);

    }

    //上拉加载
    @Override
    public void onLoadMore() {
        Log.d(TAG, "加载更多");
        mMainNewsAdapter.changeMoreStatus(TestMainAdapter.LOADING_MORE);
        mMainNewsAdapter.notifyItemChanged(mMainNewsAdapter.getItemCount() - 1);
        Log.e(TAG, "加载状态" + mMainNewsAdapter.getStatus() + "");
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                List<String> newDatas = new ArrayList<String>();
                for (int i = 0; i < 5; i++) {
                    int index = i + 1;
                    newDatas.add("more item" + index);
                }

                mMainNewsAdapter.addMoreItem(newDatas);
                mMainNewsAdapter.changeMoreStatus(TestMainAdapter.PULL_UP_LOAD_MORE);
                mMainNewsAdapter.notifyItemChanged(mMainNewsAdapter.getItemCount() - 1);
            }
        }, 2500);


    }
}

